﻿using System;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Fast.Framework.Interfaces;
using Fast.Framework.Models;


namespace Fast.Framework.Web.Test.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ProductController : ControllerBase
    {

        /// <summary>
        /// 数据库
        /// </summary>
        private readonly IDbContext<DefaultDbOptions> db;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<ProductController> logger;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="db"></param>
        public ProductController(ILogger<ProductController> logger, IDbContext<DefaultDbOptions> db)
        {
            this.db = db;
            this.logger = logger;
        }

        [HttpPost]
        public Task<int> Add(ProductModel productModel)
        {
            return db.Insert(productModel).ExecuteReturnIdentityAsync();
        }

        [HttpPost]
        public Task<int> Delete(int productId)
        {
            return db.Delete<ProductModel>().Where(w => w.ProductId == productId).ExecuteAsync();//需要显示加上条件否则 将会删除所有数据
        }

        [HttpPost]
        public Task<int> Update(ProductModel productModel)
        {
            return db.Update(productModel).Where(w => w.ProductId == productModel.ProductId).ExecuteAsync();//需要显示加上条件否则 将会更新所有数据
        }

        [HttpPost]
        public Task<List<ProductModel>> Get(QueryProductModel queryProductModel)
        {
            var ex = DynamicWhereExpression.Create<ProductModel>();//创建动态表达式

            return db.Query<ProductModel>().Where(ex.Build()).ToListAsync();
        }
    }
}

